//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by Apple on 15/11/11.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {
   
    let webView = UIWebView()
    
    //关闭界面
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充
    @objc private func fullAccount(){
        let jsString = "document.getElementById('userId').value = 'hechengchenglh@126.com' , document.getElementById('passwd').value = 'game1314';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        loadOAuthPage()
    }
    
    //view加载完成去除圈圈
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    
    
    //发送网络请求
    private func loadOAuthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    //关闭返回原来的控制器
    private func  setupUI(){
   self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }

}
//WebView所有协议方法SVP:转圈圈
extension OAuthViewController:UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request.URL)
        //absoluteString绝对路径
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        //是网页请求页面 或者请求授权页面
        if urlString.hasPrefix("https://api.weibo.com"){
            return true
        }
        if !urlString.hasPrefix(redirect_uri){
            return false
        }
        //程序走到这里  一定包含了  回调的url
        guard let query = request.URL?.query else{
            return false
        }
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
//        print(query)
//        print(code)
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            print(error)
        }
        self.dismissViewControllerAnimated(false) { () -> Void in
            NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewController, object: "Welcome")
        }
        return false
    }
    
    

}